<?php

namespace App\Service;

use App\Enums\AssetJournalTypeEnum;
use App\Enums\AssetTypeEnum;
use App\Models\UserAssetJournalModel;
use App\Models\UserAssetModel;
use Carbon\Carbon;

class UserAssetService
{

    public function getAsset($userId): ?array
    {
        $userAsset = UserAssetModel::getAssets($userId);
        return $userAsset ? $userAsset->toArray() : null;
    }

    public static function createUserAsset($userId)
    {
        $userAssetData = [
            'user_id' => $userId,
            'score' => 0,
            'coin' => 0,
            'cash' => 0
        ];
        UserAssetModel::assetCreate($userAssetData);
    }

    public function subCoin($userId, $coin, $businessId, $businessType)
    {
        UserAssetModel::subCoin($userId, $coin);
        $params = [
            'asset_type' => AssetTypeEnum::COIN,
            'journal_type' => AssetJournalTypeEnum::getValue(AssetJournalTypeEnum::DEBIT),
            'amount' => $coin,
            'business_id' => $businessId,
            'business_type' => $businessType,
            'trade_time' => Carbon::now()->toDateTimeString(),
            'status' => 1,
            'payer_user_id' => $userId,
            'payee_user_id' => 0,
        ];
        UserAssetJournalModel::commit($params);
    }

    public function addCoin($userId, $coin, $businessId, $businessType)
    {
        UserAssetModel::subCoin($userId, $coin);
        $params = [
            'asset_type' => AssetTypeEnum::COIN,
            'journal_type' => AssetJournalTypeEnum::getValue(AssetJournalTypeEnum::CREDIT),
            'amount' => $coin,
            'business_id' => $businessId,
            'business_type' => $businessType,
            'trade_time' => Carbon::now()->toDateTimeString(),
            'status' => 1,
            'payer_user_id' => $userId,
            'payee_user_id' => 0,
        ];
        UserAssetJournalModel::commit($params);
    }
}
